package com.jee.project.controller;

import com.jee.project.model.College;
import com.jee.project.model.validation.OnCreate;
import com.jee.project.repo.CollegeRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/college")
@Tag(name = "college module", description = "学院管理模块")
public class CollegeController {
    @Autowired
    private CollegeRepository collegeRepo;

    // 查询所有学院
    @GetMapping("/college")
    public Iterable<College> getAllColleges() {
        return collegeRepo.findAll();
    }

    @PostMapping("/college")
    @Operation(summary = "创建学院")
    public College addCollege(@Validated(OnCreate.class) @RequestBody College college) {
        return collegeRepo.save(college);
    }

    @PutMapping("/college/{id}")
    @Operation(summary = "修改学院", parameters = @Parameter(name = "id", in = ParameterIn.PATH))
    public College editCollege(
            @Parameter(hidden = true) @PathVariable("id") College college,
            String name) {
        college.setName(name);
        return collegeRepo.save(college);
    }

    @DeleteMapping("/college/{id}")
    @Operation(summary = "删除学院", parameters = @Parameter(name = "id", in = ParameterIn.PATH))
    public Map<String, Object> delCollege(
            @Parameter(name = "id", hidden = true)
            @PathVariable("id") College college) {
        Map<String, Object> result = new HashMap();
// 如果该college已开设了很多课程，就提示用户不能删除
        if (college.getCourses().size() > 0) {
            result.put("success", false);
            result.put("msg", "该学院下还有" + college.getCourses().size() + "门课程，请先删除对应");
        } else {
            collegeRepo.delete(college);
            result.put("success", true);
            result.put("msg", "已成功删除课程");
        }
        return result;

    }
}
